import tkinter as tk
# JSON库，用于数据存储
import json

# 示例数据
DATA = {'你好': {
      '你好|你是哪位': {
        '我是您的客服经理小智': {'什么事': 1, '不需要|不用|挂了': 0}
      },'我还有事': 0}
    }
# JSON数据
filename = "1/2/talks.json"
JSON = {}

def show_talks():
    global JSON,filename
    # 读取函数列表
    with open(filename, "r", encoding="UTF-8") as f:
        JSON = json.load(f)
        # 话术列表菜单
        menuTalks.delete(0,tk.END)
        for key, value in JSON.items():       
            menuTalks.add_command(label=key, command=lambda c=key: talk_edit(c))

# 编辑话术
def new_talk():
    global DATA
    # 重置名字和话术内容
    name.delete(0,tk.END)
    tallk.delete(1.0,tk.END)
    tallk.insert(tk.END,DATA)

# 运行添加话术窗口
def add_tallks():
    global JSON,filename
    tallk_key = name.get()
    tallk_value = tallk.get(1.0,tk.END)
    if tallk_key != "":
        JSON[tallk_key] = tallk_value
        with open(filename, 'w') as file:
            json.dump(JSON, file)
        show_talks()
    else:
        title.config(text="以上话术名称不能为空！")
    print(tallk_key,tallk_value)

# 编辑话术
def talk_edit(string):
    global JSON
    name.delete(0,tk.END)
    name.insert(tk.END,string)
    tallk.delete(1.0,tk.END)
    tallk.insert(tk.END,JSON[string])

# 创建主窗口
root = tk.Tk()
root.title("话术管理系统")
# 窗口大小("长x宽+X坐标+Y坐标")
root.geometry("1024x768")

# 创建主菜单
mainMenu = tk.Menu(root)
menuTalks = tk.Menu(mainMenu)
mainMenu.add_cascade(label="话术列表", menu=menuTalks)
# 显示菜单
root.config(menu=mainMenu)

# 表单
name = tk.Entry(root, width=45)
name.pack(fill="x")
title = tk.Label(root,text="以下话术内容必须是JSON格式")
title.pack(fill="x")
tallk = tk.Text(root, width=50, height=14, bg="#CCB")
tallk.pack(fill=tk.BOTH, expand=True)
tk.Button(root, text="新建", command=new_talk).pack(side='left')
tk.Button(root, text="保存", command=add_tallks).pack(side='right')

# 显示话术列表
show_talks()
new_talk()

root.mainloop()
